//
//  BCServiceBaseRequest.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/29.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCServiceBaseRequest.h"


#import "BCServiceBaseResponse.h"

@implementation BCServiceBaseRequest

- (NSString *)absoluteUrl {
    return UserHost;
}
- (NSString *)getSign {
    id obj = [self yy_modelToJSONObject];
    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = obj;
        NSArray *allKeys = dic.allKeys;
        if (!allKeys.count) {
            return nil;
        }
        
        NSArray *myary = [allKeys sortedArrayUsingComparator:^(NSString * obj1, NSString * obj2){
            return (NSComparisonResult)[obj1 compare:obj2 options:NSNumericSearch];
        }];
        //
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:myary.count];
        for(int i=0; i<myary.count; i++) {
            NSString *key = myary[i];
            id value = dic[key];
            if ([value isKindOfClass:NSString.class]) {
                [array addObject:value];
            }
        }
        NSString *signString = [[array componentsJoinedByString:@""] stringByAppendingString:self.app_id];
        NSString *signStringMd5 = [signString md532];
        return signStringMd5.uppercaseString;
    }
    return nil;
}

- (void)getSignString {
    NSString *sign = [self getSign];
    self.sign = sign;
}

- (void)requestServer {
    [self getSignString];
    [super requestServer];
}
//
- (BOOL)success:(NSURLSessionDataTask *)task data:(id)obj {
    BOOL success = [super success:task data:obj];
    if (success) {
        BCServiceBaseResponse *baseResp = [BCServiceBaseResponse yy_modelWithJSON:obj];
        if (baseResp.ret==200) {
            return true;
        }else {
            if (!baseResp.msg) {
                baseResp.msg = @"Unknown message";
            }
            NSError *error = [NSError errorWithDomain:baseResp.msg code:-1001 userInfo:nil];
            if (self.requestFailed) {
                self.requestFailed(error);
            }
            return false;
        }
    }
    return true;
}

@end
